<template>
  <div class="pagination">
    <button>上一页</button>
    <!-- 需要根据条件渲染，如果连续分页的第一页大于1，这个1才能出现 ,当前页等于1时,有选中样式-->
    <button
      v-if="startNumAndEndNum.start > 1"
      :class="{ active:1 ==pageNo }"
      @click="clickPage(1)"
    >
      1
    </button>
    <button v-if="startNumAndEndNum.start > 2">···</button>
    <!-- 中间部分 用v-for循环数字 -->
    <button
      v-for="(page, index) in startNumAndEndNum.end"
      :key="index"
      :class="{active:page == pageNo }"
      v-show="page > startNumAndEndNum.start - 1"
      @click="clickPage(page)"
    >
      {{ page }}
    </button>

    <button v-if="startNumAndEndNum.end < totalPage - 1">···</button>
    <!-- 当结束页小于总页数时,隐藏这个按钮,当当前页为总页数时，有选中类名 -->
    <button
      v-if="startNumAndEndNum.end < totalPage"
      :class="{active: totalPage == pageNo }"
      @click="clickPage(totalPage)"
    >
      {{ totalPage }}
    </button>
    <button>下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
    <!-- <div>{{ startNumAndEndNum }}</div> -->
  </div>
</template>

<script>
export default {
  name: "Pagination",
  data() {
    return {};
  },
  // pageNo:当前页  pageSize:每页展示多少条数据 total:一共有多少条数据 continues:分页连续页码个数
  props: ["pageNo", "pageSize", "total", "continues"],
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    startNumAndEndNum() {
      // 从this中解构数据
      const { continues, pageNo, totalPage } = this;
      let start = 0,
        end = 0;
      // 如果总页数小于连续的页数，结束页end就等于总页数
      if (continues > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);
        // 如果计算出start为0、-1，则应该从1开始，那么最后一页是分页连续页码的个数
        if (start < 1) {
          start = 1;
          end = continues;
        }
        // 如果计算出end超出总页数totalPage，则结束页end应该为总页数，那么start为总页数往前走（分页连续页码的个数-1）
        if (end > totalPage) {
          end = totalPage;
          start = totalPage - (continues - 1);
        }
        // 返回2个以上的变量要用对象
        return {start, end};
      }
    },
  },
  methods: {
    clickPage(page) {
      this.$emit("clickPage", page);
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #e1251b;
      color: #fff;
    }
  }
}
</style>